import { reqGetCode, reqUserRegister, reqUserLogin ,reqGetUserInfo,reqUserLogout} from '@/api'

const state = {
    code: '',
    token:localStorage.getItem('TOKEN_KEY'),
    token: localStorage.getItem('TOKEN_KEY'),
    userInfo: {},

}
const mutations = {
    RECEIVE_CODE(state, code) {
        state.code = code
    },

    USERLOGIN(state,token){
        state.token = token
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    // 将用户信息放入state
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    RESET_TOKEN(state){
      state.token = '',
      state.userInfo = {}
    },
}
const actions = {
    // 获取验证码
    async getCode({ commit }, phone) {
        const result = await reqGetCode(phone)
        if (result.code === 200) {
            commit('RECEIVE_CODE', result.data)
            return result.data
        } else {
            return Promise.reject(new Error('failed'))
        }
    },

    //  提交注册信息
    async UserRegister({ commit }, userInfo) {
        const result = await reqUserRegister(userInfo)
        if (result.code === 200) {
            return '注册成功'
        } else {
            return Promise.reject(new Error('注册失败'))
        }
    },

    // 登录
    async UserLogin({ commit }, loginInfo) {
        const result = await reqUserLogin(loginInfo)
        if (result.code === 200) {
            commit('USERLOGIN', result.data.token)
            // 本地存储
            localStorage.setItem('TOKEN_KEY', result.data.token)
            return 'ok'
        } else {
            return Promise(new Error('登录失败'))
        }
    },

    // 获取用户信息
    async getUserInfo({commit}){
      const result = await reqGetUserInfo()
      if(result.code === 200){
          commit('GETUSERINFO',result.data)
          return 'ok'
      }else{
        return Promise(new Error('获取信息失败'))
      }
    },
    async resetToken({commit}){
      commit('RESET_TOKEN') 
      localStorage.removeItem('TOKEN_KEY')
    },
    async userLogout({commit,dispatch}){
      const result = await reqUserLogout()
      if(result.code === 200){
        dispatch('resetToken') 
        return 'ok'
      }else{
        return Promise.reject(new Error('failed'))
      }
    },
}

const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}